
var signalR = (function () {
  const app = getApp()
  let recordCode = 0x1e;
  let recordString = String.fromCharCode(recordCode);
  
   
  let _events=new Array(); 
   
  const log = require('log.js'); 
  const util = require('util.js'); 
  //初始化相关事件
  //消息发送事件
  _events['send'] = function (obj) {
    console.log(obj);
  };
  //消息接收事件
  _events['receive']=function(message){
    console.log(message);
  };
  //连接事件
  _events['connection']= function () {
    console.log(message);
  };
  //连接关闭事件
  _events['close']= function () {
    console.log('连接已经关闭');
  };
  //连接异常处理事件
  _events['error'] = function (ex) {
    console.log(ex);
  };
  return {
    IsConnectioned: function()
    { 
      return app.isConnectioned;
    },
    //事件绑定
    on:function(eventName,eventMethod){
      if (_events[eventName] != null && _events[eventName]!='undefined'){
        _events[eventName] = eventMethod;
      }
    },
    //连接方法
    connection: function (url) {
      let self = this;
      log.info("进入signalR准备打开连接Hub2-->"+url);
      console.log("进入signalR准备打开连接Hub2-->"+url);
      wx.connectSocket({
        url: url,
        header: {'content-type': 'application/json'},
        success: function(){
          log.info("connectSocket成功");
          console.log("connectSocket成功"); 
        },
        fail: function(err){
           log.info("connectSocket失败");
           console.log("connectSocket失败"); 
        },
        complete: function(err){ 
           log.info("connectSocket-->complete");
           console.log("connectSocket-->complete"); 
        }
      });
      
      wx.onSocketOpen(function () {
          let handshakeRequest = {
            protocol: 'json',
            version: 1
          };
          log.info("onSocketOpen回调成功");
          console.log("onSocketOpen回调成功"); 
          let senddata = `${JSON.stringify(handshakeRequest)}${recordString}`;
          log.info("onSocketOpen回调响应-->"+senddata);
          console.log("onSocketOpen回调响应-->"+senddata);
          app.isConnectioned = true; 
          
          util.tryHideFullScreenLoading(false);
          wx.sendSocketMessage({
            data: senddata,
          });
          _events['connection'](); 
      });
     
      wx.onSocketClose(function () {
         
          app.isConnectioned = false;
          _events['close']();
          log.info("onSocketClose连接关闭");
          console.log("onSocketClose连接关闭");
      });
      
      //接收到消息
      wx.onSocketMessage(function (res) {
         try { 
            let jsonstr = String(res.data).replace(recordString, '');
            if (jsonstr.indexOf('{}{') > -1){
              jsonstr = jsonstr.replace('{}', '');
            }
            jsonstr = jsonstr.replace('','');
            //去掉空格（两种方法都可以）
            jsonstr = jsonstr.replace(/\ +/g,"");
            jsonstr = jsonstr.replace(/[ ]/g,"") 
            //去掉回车换行        
            jsonstr = jsonstr.replace(/[\r\n]/g,""); 
            //去掉 ‘-’
            //jsonstr = jsonstr.replace(/-/g, "");
            //
            let regex = new RegExp('"type"', 'g'); // 使用g表示整个字符串都要匹配
            let result = jsonstr.match(regex);          //match方法可在字符串内检索指定的值，或找到一个或多个正则表达式的匹配。
            let count=!result ? 0 : result.length; 
            //
            let ptJson = '';
            let hdGv = false;
            let tcJson = '';
            if(count>1){
                  log.error('需要拆分的包：' + jsonstr);
                  var positions = new Array();
                  var pos = jsonstr.indexOf('"type"');
                      while(pos>-1){
                          positions.push(pos);
                          pos = jsonstr.indexOf('"type"',pos+1);
                      } 

                  for(let i=0;i<positions.length;i++)
                  {
                      let jons='';
                      if(i<positions.length-1)
                      {
                            jons = jsonstr.substr(positions[i]-1,positions[i+1]-3); 
                            if(!jons.startsWith('{')){
                              jons='{'+jons;
                            }
                      }
                      else 
                      {
                           jons = jsonstr.substr(positions[i]-1, jsonstr.length-positions[i]+1); 
                           if(!jons.startsWith('{')){
                            jons='{'+jons;
                           }
                           if(!jons.endsWith('}')){
                            jons = jons.substr(0,jons.length-1)
                           }
                      }
                      if(!jons.endsWith('}'))
                      {
                                if(!jons.endsWith(']'))
                                {
                                   if(!jons.endsWith('"'))
                                   {
                                       jons=jons+'"]}';
                                   }
                                   else
                                   {
                                      jons=jons+']}';
                                   }
                                }
                                else
                                {
                                   jons=jons+'}';
                                }
                      }
                      if(jons.indexOf('titckets')>-1)
                      {
                          log.error('过滤到的titckets包：' + jons);
                          tcJson = jons;
                          hdGv = true;
                          break;
                      }
                      else
                      {
                          log.error('过滤到的普通包：' + jons);
                          hdGv = true;
                          if(ptJson==='')
                          {
                              ptJson = jons;
                          } 
                      }
                  } 

            }
            if(hdGv){
                if(tcJson!=''){
                  jsonstr = tcJson;
                  log.warn('过滤到的可发送1' + jsonstr);
                }
                else 
                {
                    if(ptJson!=''){
                       jsonstr = ptJson; 
                       log.warn('过滤到的可发送2' + jsonstr);
                    }
                }
            }
            
            let obj = JSON.parse(jsonstr);
            console.warn('接收到的消息-->'+JSON.stringify(obj));
            //当收到返回消息type=1（调用方法）
            if (obj.type === 1) {
              _events['receive'](obj.arguments[0]);
            }
        } catch (ex) {
          console.error('异常：' + ex);
          console.error('收到服务器内容：' + res.data);
          log.error('接收异常：' + ex);
          log.error('接收到服务器内容：' + res.data);
        }
      });

      wx.onSocketError(function (ex) { 
        app.isConnectioned = false;
        _events['error'](ex);
        log.error("onSocketError-->"+ex.errMsg);
        console.error("onSocketError-->"+ex.errMsg); 
      });
    },
    abortConnection: function () { 
      app.isConnectioned = false;
      console.log(String(this.abortConnection.name));
      log.info("abortConnection-->"+String(this.abortConnection.name));
      console.log("abortConnection-->"+String(this.abortConnection.name)); 
      wx.closeSocket();
    },
    sendMessage: function (data) { 
      if (!app.isConnectioned) {
        log.info("sendMessage失败");
        console.log("sendMessage失败"); 
        _events['error']('未连接-发送失败');
        return;
      }
      let args=new Array();
      args.push(data);
      let body = {
        arguments: args,   //SignalR服务端接收时必须为数组参数
        target: 'Send',        //SignalR端方法
        type: 1,
      };
      
      
      //发送的数据，分隔符结尾：
      let senddata = `${JSON.stringify(body)}${recordString}`;
      wx.sendSocketMessage({
        data: senddata,
        success: function(res){
          _events['send']("sendMessageOk-->"+res.errMsg);
          //log.info("sendMessageOk-->"+senddata);
          //console.log("sendMessageOk-->"+senddata); 
        },
        fail: function(ex){
          log.info("sendMessageFail-->"+JSON.stringify(ex));
          console.log("sendMessageFail-->"+JSON.stringify(ex));  
        }
      });
    }
  }
});
module.exports = {
  signalR: signalR
}